<template>
  <el-input v-model.trim="queryFormModel.checkCode" prefix-icon="el-icon-message" type="text" maxlength="10" placeholder="请输入验证码">
    <span slot="suffix">
      <i v-if="yzmLoading" class="el-icon-loading phone-code-loading" />
      <span v-else>
        <span
          v-if="count===120"
          class="phone-code-btn count-text"
          :class="{'phoneCode-isdisabled':!queryFormModel.username&&!queryFormModel.phone}"
          @click="getPhoneCode"
        >获取验证码</span>
        <span v-else class="count-text">{{ count }} s</span>
      </span>
    </span>
  </el-input>
</template>

<script>
import { sendPhoneCode } from '@/api/login';

export default {
  props: {
    checkType: {
      type: Number,
      default: 1 // 0-注册验证 1-登录验证 2-改密验证
    },
    queryForm: {
      type: Object,
      default: () => { }
    }
  },
  data() {
    return {
      yzmLoading: false,
      count: 120,
      yzmTimer: null
    };
  },
  computed: {
    queryFormModel: {
      get() {
        return this.queryForm;
      },
      set(v) {
        this.$emit('update:queryForm', v);
      }
    }
  },
  beforeDestroy() {
    this.clearTimer();
  },
  methods: {
    clearTimer() {
      clearInterval(this.yzmTimer);
      this.count = 120;
    },
    getPhoneCode() {
      if (this.count !== 120) return;
      if (!this.queryFormModel.username && !this.queryFormModel.phone) return;
      this.yzmLoading = true;
      const { username, phone } = this.queryFormModel;
      sendPhoneCode({
        username: username || phone,
        checkType: this.checkType
      }).then(({ value, success }) => {
        if (success) {
          this.$notify({
            title: '发送成功',
            message: value || '验证码已发,请注意查收!',
            type: 'success'
          });
          this.count--;
          this.yzmTimer = setInterval(() => {
            this.count--;
            if (this.count <= 0) {
              this.clearTimer();
            }
          }, 1000);
          if (value) {
            const result = value.split('：');// 本地/测试,自动填充验证码
            if (Number.isInteger(Number(result[1]))) {
              this.$emit('setPhoneCode', result[1]);
            }
          }
        } else {
          this.clearTimer();
        }
      }).catch(() => this.clearTimer())
        .finally(() => { this.yzmLoading = false; });
    }
  }
};
</script>

<style lang="scss" scoped>
.count-text {
  height: 34px;
  line-height: 36px;
  border-radius: 4px;
  font-size: 14px;
  z-index: 2;
  color: #1c8be4;
}

.phone-code-btn {
  cursor: pointer;
  user-select: none;
}
.phoneCode-isdisabled {
  cursor: not-allowed;
  color: rgba(28, 139, 228, 0.5);
}
.phone-code-loading {
  color: #1c8be4;
  font-size: 14px;
}
</style>
